<template>
  <div id="addPicturePage">
    <h2 style="margin-bottom: 16px; text-align: center">
      {{ route.query?.id ? '修改图片' : '创建图片' }}
    </h2>
    <a-typography-text v-if="spaceId" type="secondary">
      上传至空间:
      <a :href="`/space/${spaceId}`" target="_blank">{{ spaceId }}</a>
    </a-typography-text>
    <!-- 选择上传方式 -->
    <a-tabs v-model:activeKey="uploadType">
      <a-tab-pane key="file" tab="文件上传">
        <!-- 图片上传组件 -->
        <PictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess"
      /></a-tab-pane>
      <a-tab-pane key="url" tab="URL 上传" force-render>
        <!-- Url图片上传组件 -->
        <UrlPictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess"
      /></a-tab-pane>
    </a-tabs>
    <!-- 图片编辑区域 -->
    <div v-if="picture" class="edit-bar">
      <a-space>
        <a-button :icon="h(EditOutlined)" @click="doEditPicture">编辑图片</a-button>
        <a-button :icon="h(FullscreenOutlined)" type="primary" @click="doImagePainting"
          >AI编辑图片</a-button
        ></a-space
      >
      <imageCropper
        ref="imageCropperRef"
        :imageUrl="picture?.url"
        :picture="picture"
        :onSuccess="onCropperSuccess"
        :spaceId="spaceId"
        :space="space"
      />

      <ImageOutPainting
        ref="imageOutPaintingRef"
        :picture="picture"
        :spaceId="spaceId"
        :onSuccess="onImageOutPaintingSuccess"
      />
    </div>

    <!-- 图片信息表单 -->
    <a-form v-if="picture" layout="vertical" :model="pictureForm" @finish="handleSubmit">
      <a-form-item label="名称">
        <a-input v-model:value="pictureForm.name" placeholder="输入图片名称" allow-clear />
      </a-form-item>
      <a-form-item label="简介">
        <a-textarea
          v-model:value="pictureForm.introduction"
          placeholder="输入图片简介"
          :autoSize="{ minRows: 2, maxRows: 5 }"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="分类">
        <a-auto-complete
          v-model:value="pictureForm.category"
          placeholder="请选择图片分类"
          :options="categoryOptions"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="标签">
        <a-select
          v-model:value="pictureForm.tags"
          mode="tags"
          placeholder="请选择图片标签"
          :options="tagOptions"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">创建</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import ImageCropper from '@/components/imageCropper.vue'
import {
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController'
import PictureUpload from '@/components/PictureUpload.vue'
import UrlPictureUpload from '@/components/UrlPictureUpload.vue'
import { message } from 'ant-design-vue'
import { computed, onMounted, reactive, ref, h } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { EditOutlined, FullscreenOutlined } from '@ant-design/icons-vue'
import ImageOutPainting from '@/components/ImageOutPainting.vue'
import { watchEffect } from 'vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController'
const picture = ref<API.PictureVO>()
const pictureForm = reactive<API.PictureEditRequest>({})
const uploadType = ref<'file' | 'url'>('file')
const router = useRouter()
const route = useRoute()
//空间id
const spaceId = computed(() => {
  return route.query?.spaceId
})
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
}

/**
 * 提交表单
 */
function handleSubmit() {
  const pictureId = picture.value?.id
  if (!pictureId) {
    message.error('请上传图片')
  } else {
    editPictureUsingPost({ id: pictureId, spaceId: spaceId.value, ...pictureForm })
      .then((res) => {
        if (res.data.code === 200) {
          message.success('创建成功')
          // 跳转到图片详情页面
          router.push(`/picture/${pictureId}`)
        } else {
          message.error('创建失败：' + res.data.data)
        }
      })
      .catch(() => {
        message.error('创建异常')
      })
  }
}

//获取分类
const categoryOptions = ref<{ value: string; label: string }[]>([])
const tagOptions = ref<{ value: string; label: string }[]>([])
/**
 * 获取分类和标签
 */
function getTagAndCategory() {
  const pictureId = picture.value?.id

  listPictureTagCategoryUsingGet()
    .then((res) => {
      if (res.data.code === 200) {
        tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
          return {
            value: data,
            label: data,
          }
        })
        categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
          return {
            value: data,
            label: data,
          }
        })
      } else {
        message.error('获取失败' + res.data.data)
      }
    })
    .catch(() => {
      message.error('获取分类和标签异常')
    })
}
const space = ref<API.SpaceVO>()

// 获取空间信息
const fetchSpace = async () => {
  // 获取数据
  if (spaceId.value) {
    const res = await getSpaceVoByIdUsingGet({
      id: spaceId.value,
    })
    if (res.data.code === 200 && res.data.data) {
      space.value = res.data.data
    }
  }
}

watchEffect(() => {
  fetchSpace()
})

onMounted(() => {
  getTagAndCategory()
  getOldPicture()
})
const imageCropperRef = ref()
//编辑图片裁剪
const doEditPicture = () => {
  imageCropperRef.value?.openModel()
}
//编辑成功事件
const onCropperSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

const imageOutPaintingRef = ref()
//打开弹窗
const doImagePainting = () => {
  imageOutPaintingRef.value?.openModel()
}
//更改图片
const onImageOutPaintingSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

//获取老数据
const getOldPicture = async () => {
  const pictureId = route.query?.id
  if (pictureId) {
    const res = await getPictureVoByIdUsingGet({ id: pictureId })
    if (res.data.code === 200 && res.data.data) {
      const data = res.data.data
      picture.value = data
      pictureForm.name = data.name
      pictureForm.introduction = data.introduction
      pictureForm.tags = data.tags
      pictureForm.category = data.category
    }
  }
}
</script>
<style scoped>
#addPicturePage {
  max-width: 720px;
  margin: 0 auto;
}
#addPicturePage .edit-bar {
  margin: 16px 0;
  text-align: center;
}
</style>